package com.zsyc.model;

import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.zsyc.util.DatabaseManager;

/**
 * 任务模型类
 */
public class Task {
    private static final Logger LOGGER = Logger.getLogger(Task.class.getName());
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    private Integer taskId;
    private String title;
    private String description;
    private LocalDate dueDate;
    private String category;
    private boolean isCompleted;
    private String createdAt;
    private boolean enableReminder;
    private int reminderTime;
    private String reminderUnit;
    
    public Task() {}
    
    public Task(String title, String description, LocalDate dueDate, String category) {
        this.title = title;
        this.description = description;
        this.dueDate = dueDate;
        this.category = category;
        this.isCompleted = false;
        this.enableReminder = false;
        this.reminderTime = 2;
        this.reminderUnit = "小时";
    }
    
    public Task(String title, String description, LocalDate dueDate, String category, boolean enableReminder, int reminderTime, String reminderUnit) {
        this.title = title;
        this.description = description;
        this.dueDate = dueDate;
        this.category = category;
        this.isCompleted = false;
        this.enableReminder = enableReminder;
        this.reminderTime = reminderTime;
        this.reminderUnit = reminderUnit;
    }
    
    // Getters and Setters
    public Integer getTaskId() { return taskId; }
    public void setTaskId(Integer taskId) { this.taskId = taskId; }
    
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
    
    public LocalDate getDueDate() { return dueDate; }
    public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; }
    
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    
    public boolean isCompleted() { return isCompleted; }
    public boolean getCompleted() { return isCompleted; }
    public void setCompleted(boolean completed) { isCompleted = completed; }
    
    public String getCreatedAt() { return createdAt; }
    public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
    
    public boolean isEnableReminder() { return enableReminder; }
    public void setEnableReminder(boolean enableReminder) { this.enableReminder = enableReminder; }
    
    public int getReminderTime() { return reminderTime; }
    public void setReminderTime(int reminderTime) { this.reminderTime = reminderTime; }
    
    public String getReminderUnit() { return reminderUnit; }
    public void setReminderUnit(String reminderUnit) { this.reminderUnit = reminderUnit; }
    
    public boolean save() {
        String sql = "INSERT INTO task (title, description, due_date, category, is_completed, enable_reminder, reminder_time, reminder_unit) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setDate(3, dueDate != null ? Date.valueOf(dueDate) : null);
            pstmt.setString(4, category);
            pstmt.setBoolean(5, isCompleted);
            pstmt.setBoolean(6, enableReminder);
            pstmt.setInt(7, reminderTime);
            pstmt.setString(8, reminderUnit);
            
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                // 获取最后插入的ID
                try (Statement stmt = conn.createStatement();
                     ResultSet rs = stmt.executeQuery("SELECT last_insert_rowid()")) {
                    if (rs.next()) {
                        this.taskId = rs.getInt(1);
                    }
                }
                LOGGER.info("任务保存成功: " + title + " (ID: " + taskId + ")");
                return true;
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "保存任务失败: " + title, e);
        }
        return false;
    }
    
    /**
     * 更新任务
     */
    public boolean update() {
        String sql = "UPDATE task SET title = ?, description = ?, due_date = ?, category = ?, is_completed = ?, enable_reminder = ?, reminder_time = ?, reminder_unit = ? WHERE task_id = ?";
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, title);
            pstmt.setString(2, description);
            pstmt.setDate(3, dueDate != null ? Date.valueOf(dueDate) : null);
            pstmt.setString(4, category);
            pstmt.setBoolean(5, isCompleted);
            pstmt.setBoolean(6, enableReminder);
            pstmt.setInt(7, reminderTime);
            pstmt.setString(8, reminderUnit);
            pstmt.setInt(9, taskId);
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "更新任务失败", e);
            return false;
        }
    }
    
    /**
     * 删除任务
     */
    public boolean delete() {
        String sql = "DELETE FROM task WHERE task_id = ?";
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, taskId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "删除任务失败", e);
            return false;
        }
    }
    
    public static List<Task> getAllTasks() {
        List<Task> tasks = new ArrayList<>();
        String sql = "SELECT * FROM task ORDER BY due_date ASC, created_at DESC";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                Task task = mapResultSetToTask(rs);
                tasks.add(task);
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取任务列表失败", e);
        }
        return tasks;
    }
    
    /**
     * 根据分类获取任务
     */
    public static List<Task> getTasksByCategory(String category) {
        List<Task> tasks = new ArrayList<>();
        String sql = "SELECT * FROM task WHERE category = ? ORDER BY due_date ASC, created_at DESC";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, category);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Task task = mapResultSetToTask(rs);
                    tasks.add(task);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "根据分类获取任务失败", e);
        }
        return tasks;
    }
    
    /**
     * 获取所有任务分类
     */
    public static List<String> getAllCategories() {
        List<String> categories = new ArrayList<>();
        String sql = "SELECT DISTINCT category FROM task ORDER BY category";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            
            while (rs.next()) {
                categories.add(rs.getString("category"));
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取任务分类失败", e);
        }
        return categories;
    }
    
    /**
     * 获取即将到期的任务
     */
    public static List<Task> getUpcomingTasks(int days) {
        List<Task> tasks = new ArrayList<>();
        String sql = "SELECT * FROM task WHERE due_date <= ? AND is_completed = FALSE ORDER BY due_date ASC";
        
        try (Connection conn = DatabaseManager.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            LocalDate targetDate = LocalDate.now().plusDays(days);
            pstmt.setDate(1, Date.valueOf(targetDate));
            
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Task task = mapResultSetToTask(rs);
                    tasks.add(task);
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取即将到期的任务失败", e);
        }
        return tasks;
    }
    
    /**
     * 将ResultSet映射到Task对象
     */
    private static Task mapResultSetToTask(ResultSet rs) throws SQLException {
        Task task = new Task();
        task.setTaskId(rs.getInt("task_id"));
        task.setTitle(rs.getString("title"));
        task.setDescription(rs.getString("description"));
        
        Date dueDate = rs.getDate("due_date");
        if (dueDate != null) {
            task.setDueDate(dueDate.toLocalDate());
        }
        
        task.setCategory(rs.getString("category"));
        task.setCompleted(rs.getBoolean("is_completed"));
        task.setCreatedAt(rs.getString("created_at"));
        
        // 读取提醒设置（如果列存在）
        try {
            task.setEnableReminder(rs.getBoolean("enable_reminder"));
            task.setReminderTime(rs.getInt("reminder_time"));
            task.setReminderUnit(rs.getString("reminder_unit"));
        } catch (SQLException e) {
            // 如果列不存在，使用默认值
            task.setEnableReminder(false);
            task.setReminderTime(2);
            task.setReminderUnit("小时");
        }
        
        return task;
    }
}
